package cn.edu.dgut.css.sai.jpa.springdatajpaspecifications.specifications;

import cn.edu.dgut.css.sai.jpa.springdatajpaspecifications.model.Employee;
import cn.edu.dgut.css.sai.jpa.springdatajpaspecifications.model.Employee_;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @author sai
 * @since 2020-12-13
 */
public class EmployeeSpecification {

    /**
     * 原生使用Criteria API构建动态查询的过程也可以参考：{@link SimpleJpaRepository#findAll(Specification)}
     */
    public static Specification<Employee> hasFirstName(String firstname) {

        // 匿名内部类
        // 有了spring data jpa的帮助，我们只需要专心写 Predicate 就好，其它交由框架去做。
        return new Specification<Employee>() {

            @Override
            public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {

                return criteriaBuilder.equal(root.get(Employee_.FIRSTNAME), firstname);

            }
        };
    }

    public static Specification<Employee> containsLastName(String lastname) {
        return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.like(root.get(Employee_.LASTNAME), "%" + lastname + "%");
    }

    public static Specification<Employee> hasDepartment(String department) {
        return (root, criteriaQuery, criteriaBuilder) -> criteriaBuilder.equal(root.get(Employee_.DEPARTMENT), department);
    }
}
